<template>
<div class="login-container">
    <!-- 头部 -->
    <header class="header">
        <div class="header-content">
            <a href="#" @click="goBack()" class="back-btn">
                <svg t="1751614585251" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" 
                    p-id="1471" width="20" height="20">
                    <path d="M790.865959 73.216062 322.123178 512.062492l468.74278 438.746442c16.397998 16.697962 16.397998 43.894642 0 60.592603-16.397998 16.697962-42.894764 16.697962-59.292762 0l-498.839107-466.943c-8.698938-8.898914-12.398487-20.797461-11.898548-32.496033-0.599927-11.698572 3.099622-23.497132 11.898548-32.496033l498.839107-466.943c16.397998-16.697962 42.894764-16.697962 59.292762 0C807.263957 29.421409 807.263957 56.518101 790.865959 73.216062z" 
                        fill="#272636" 
                        p-id="1472">
                    </path>
                </svg>
            </a>
            <div class="header-title">{{ currentTab === 'login' ? '登录' : '注册' }}</div>
        </div>
    </header>

    <main class="main-content">
        <div class="form-container">
            <!-- 选项卡切换 -->
            <div class="tab-switch">
                <div 
                    class="tab-item" 
                    :class="{ active: currentTab === 'login' }"
                    @click="switchTab('login')"
                >
                    登录
                </div>
                <div 
                    class="tab-item" 
                    :class="{ active: currentTab === 'register' }"
                    @click="switchTab('register')"
                >
                    注册
                </div>
            </div>

            <!-- 登录表单 -->
            <div v-if="currentTab === 'login'" class="login-form">
                <div class="logo">LumenTracks</div>
                <div class="welcome-text">欢迎回来</div>
                
                <!-- 登录方式切换 -->
                <div class="login-type-switch">
                    <div 
                        class="type-item" 
                        :class="{ active: loginType === 'phone' }"
                        @click="switchLoginType('phone')"
                    >
                        手机号登录
                    </div>
                    <div 
                        class="type-item" 
                        :class="{ active: loginType === 'email' }"
                        @click="switchLoginType('email')"
                    >
                        邮箱登录
                    </div>
                </div>
                
                <!-- 手机号登录表单 -->
                <div v-if="loginType === 'phone'" class="form-group">
                    <label for="phone">手机号</label>
                    <input type="tel" id="phone" v-model="userLoginDTO.phone" placeholder="请输入手机号" maxlength="11">
                    <div class="error-message" v-if="phoneError">{{ phoneError }}</div>
                </div>
                
                <!-- 邮箱登录表单 -->
                <div v-if="loginType === 'email'" class="form-group">
                    <label for="email">邮箱</label>
                    <input type="email" id="email" v-model="userLoginDTO.email" placeholder="请输入邮箱">
                    <div class="error-message" v-if="emailError">{{ emailError }}</div>
                </div>
                
                <div class="form-group">
                    <label for="password">密码</label>
                    <input type="password" id="password" v-model="userLoginDTO.password" placeholder="请输入密码">
                    <div class="error-message" v-if="passwordError">{{ passwordError }}</div>
                </div>
                
                <div class="form-options">
                    <div class="remember-me">
                        <input type="checkbox" id="remember" v-model="rememberMe">
                        <label for="remember">记住我</label>
                    </div>
                    <a href="#" class="forgot-password">忘记密码?</a>
                </div>
                
                <button class="btn-login" @click="login" v-loading.fullscreen.lock="fullscreenLoading">登录</button>
                
                <div class="other-login">
                    <div class="divider">
                        <span>其他登录方式</span>
                    </div>
                    <div class="social-login">
                        <div class="social-icon">微信</div>
                        <div class="social-icon">QQ</div>
                        <div class="social-icon">微博</div>
                    </div>
                </div>
            </div>

            <!-- 注册表单 -->
            <div v-if="currentTab === 'register'" class="register-form">
                <div class="logo">LumenTracks</div>
                <div class="welcome-text">创建新账户</div>
                
                <div class="form-group">
                    <label for="username">用户名</label>
                    <input type="text" id="username" v-model="userRegisterDTO.username" placeholder="请输入用户名">
                    <div class="error-message" v-if="usernameError">{{ usernameError }}</div>
                </div>
                
                <div class="form-group">
                    <label>联系方式（至少填写一项）</label>
                    <div class="contact-options">
                        <div class="contact-item">
                            <input type="tel" v-model="userRegisterDTO.phone" placeholder="手机号" maxlength="11">
                            <div class="error-message" v-if="phoneError">{{ phoneError }}</div>
                        </div>
                        <div class="contact-divider">或</div>
                        <div class="contact-item">
                            <input type="email" v-model="userRegisterDTO.email" placeholder="邮箱">
                            <div class="error-message" v-if="emailError">{{ emailError }}</div>
                        </div>
                    </div>
                </div>
                
                <div class="form-group">
                    <label for="reg-password">密码</label>
                    <input type="password" id="reg-password" v-model="userRegisterDTO.password" placeholder="请输入密码">
                    <div class="error-message" v-if="passwordError">{{ passwordError }}</div>
                </div>
                
                <div class="form-group">
                    <label for="confirm-password">确认密码</label>
                    <input type="password" id="confirm-password" v-model="userRegisterDTO.confirmPassword" placeholder="请再次输入密码">
                    <div class="error-message" v-if="confirmPasswordError">{{ confirmPasswordError }}</div>
                </div>
                
                <button class="btn-register" @click="register" v-loading.fullscreen.lock="fullscreenLoading">注册</button>
            </div>
        </div>
    </main>
</div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api/index.js'
import { CacheComponentStore } from '@/stores/cache/cacheComponentStore'
import { UserInfoStore } from '@/stores/userInfoStore'
import { TipStore } from '@/stores/tipStore'

const router = useRouter()

const cache_Store = CacheComponentStore()
const user_Store = UserInfoStore()
const tip_Store = TipStore()

// 当前选项卡
const currentTab = ref('login') // 'login' 或 'register'
// 登录方式
const loginType = ref('phone') // 'phone' 或 'email'

// 表单数据
const userLoginDTO = ref({
    phone: '',
    email: '',
    password: ''
})

const userRegisterDTO = ref({
    username: '',
    phone: '',
    email: '',
    password: '',
    confirmPassword: ''
})

const rememberMe = ref(false)

// 错误信息
const phoneError = ref('')
const emailError = ref('')
const passwordError = ref('')
const usernameError = ref('')
const confirmPasswordError = ref('')

const fullscreenLoading = ref(false) // 全屏加载标识

// 切换选项卡
function switchTab(tab) {
    currentTab.value = tab
    // 清除错误信息
    clearErrors()
}

// 切换登录方式
function switchLoginType(type) {
    loginType.value = type
    // 清除错误信息
    clearErrors()
}

// 清除错误信息
function clearErrors() {
    phoneError.value = ''
    emailError.value = ''
    passwordError.value = ''
    usernameError.value = ''
    confirmPasswordError.value = ''
}

// 返回上一页
function goBack() {
    router.go(-1)
}

// 登录表单验证
function validateLoginForm() {
    let isValid = true
    clearErrors()
    
    if (loginType.value === 'phone') {
        // 验证手机号
        if (!userLoginDTO.value.phone) {
            phoneError.value = '请输入手机号'
            isValid = false
        } else if (!/^1[3-9]\d{9}$/.test(userLoginDTO.value.phone)) {
            phoneError.value = '请输入正确的手机号'
            isValid = false
        }
    } else {
        // 验证邮箱
        if (!userLoginDTO.value.email) {
            emailError.value = '请输入邮箱'
            isValid = false
        } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userLoginDTO.value.email)) {
            emailError.value = '请输入正确的邮箱格式'
            isValid = false
        }
    }
    
    // 验证密码
    if (!userLoginDTO.value.password) {
        passwordError.value = '请输入密码'
        isValid = false
    } else if (userLoginDTO.value.password.length < 3) {
        passwordError.value = '密码长度不能少于3位'
        isValid = false
    }
    
    return isValid
}

// 注册表单验证
function validateRegisterForm() {
    let isValid = true
    clearErrors()
    
    // 验证用户名
    if (!userRegisterDTO.value.username) {
        usernameError.value = '请输入用户名'
        isValid = false
    } else if (userRegisterDTO.value.username.length < 2) {
        usernameError.value = '用户名长度不能少于2位'
        isValid = false
    }
    
    // 验证联系方式（手机号或邮箱至少填写一项）
    const hasPhone = userRegisterDTO.value.phone
    const hasEmail = userRegisterDTO.value.email
    
    if (!hasPhone && !hasEmail) {
        phoneError.value = '手机号或邮箱至少填写一项'
        emailError.value = '手机号或邮箱至少填写一项'
        isValid = false
    } else {
        // 如果填写了手机号，验证格式
        if (hasPhone && !/^1[3-9]\d{9}$/.test(userRegisterDTO.value.phone)) {
            phoneError.value = '请输入正确的手机号'
            isValid = false
        }
        
        // 如果填写了邮箱，验证格式
        if (hasEmail && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userRegisterDTO.value.email)) {
            emailError.value = '请输入正确的邮箱格式'
            isValid = false
        }
    }
    
    // 验证密码
    if (!userRegisterDTO.value.password) {
        passwordError.value = '请输入密码'
        isValid = false
    } else if (userRegisterDTO.value.password.length < 3) {
        passwordError.value = '密码长度不能少于3位'
        isValid = false
    }
    
    // 验证确认密码
    if (!userRegisterDTO.value.confirmPassword) {
        confirmPasswordError.value = '请确认密码'
        isValid = false
    } else if (userRegisterDTO.value.password !== userRegisterDTO.value.confirmPassword) {
        confirmPasswordError.value = '两次输入的密码不一致'
        isValid = false
    }
    
    return isValid
}

// 登录
async function login() {
    if (!validateLoginForm()) return
    
    try {
        // 1.全局加载中，防止用户重复点击
        fullscreenLoading.value = true

        // 2.调用登录api
        const loginRes = await api.User_Login(userLoginDTO.value)

        if (loginRes.data.code != 1) {
            return
        }

        // 3.处理返回的用户数据
        // 3.1.存储jwt令牌到本地
        localStorage.setItem(user_Store.userToken, loginRes.data.data)

        // 3.2.解析用户信息，存储到Pinia中
        const jwtParseRes = await api.User_GetUserInfoByJwt(loginRes.data.data)
        user_Store.setUserInfo(jwtParseRes.data.data)

        // 3.3.解除加载状态
        fullscreenLoading.value = false
        cache_Store.reload('Profile', 'index') // 刷新个人主页组件
        cache_Store.reload('Home', 'index') // 刷新首页组件
        tip_Store.successTip('登录成功')
        
        // 4.跳转到个人中心页面
        router.replace('/Index/Profile')
        
    } catch (error) {
        console.error('登录失败：', error)
    } finally { 
        fullscreenLoading.value = false // 解除加载状态
    }
}

// 注册
async function register() {
    if (!validateRegisterForm()) return
    
    try {
        const userRegDTO = {
            username: userRegisterDTO.value.username,
            phone: userRegisterDTO.value.phone,
            email: userRegisterDTO.value.email,
            password: userRegisterDTO.value.password
        }

        // 调用注册API
        const response = await api.register(userRegDTO)
        
        // 如果API调用成功，处理返回结果
        if (response && response.data && response.data.code == 1) {
            // 提示注册成功
            tip_Store.successTip('注册成功，请登录')
            
            // 切换到登录选项卡
            currentTab.value = 'login'
            
            // 清空表单
            userRegisterDTO.value = {
                username: '',
                phone: '',
                email: '',
                password: '',
                confirmPassword: ''
            }
        } else {
            // API返回错误信息
            tip_Store.errorTip(response?.data?.msg || '注册失败，该手机号或邮箱可能已被注册')
        }
    } catch (error) {
        console.log('注册API调用失败', error)
        tip_Store.errorTip('注册失败，请稍后再试')
    } finally {
        fullscreenLoading.value = false
    }
}
</script>

<style lang="scss" scoped>
.login-container {
    min-height: 100vh;
    background-color: #f8f9fa;
}

.header {
    background: white;
    padding: 15px 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
}

.header-content {
    display: flex;
    align-items: center;
}

.back-btn {
    margin-right: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
}

.header-title {
    font-size: 18px;
    font-weight: 600;
    flex-grow: 1;
    text-align: center;
    margin-right: 24px; /* 为了视觉平衡，因为左边有返回按钮 */
}

.main-content {
    padding: 80px 20px 20px;
}

.form-container {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 15px rgba(0,0,0,0.05);
    overflow: hidden;
}

.tab-switch {
    display: flex;
    border-bottom: 1px solid #eee;
}

.tab-item {
    flex: 1;
    text-align: center;
    padding: 15px 0;
    font-size: 16px;
    color: #666;
    cursor: pointer;
    transition: all 0.3s;
    position: relative;
}

.tab-item.active {
    color: #ff6b6b;
    font-weight: 600;
}

.tab-item.active::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 2px;
    background-color: #ff6b6b;
}

.login-form, .register-form {
    padding: 30px 20px;
}

.logo {
    text-align: center;
    font-size: 28px;
    font-weight: bold;
    color: #ff6b6b;
    margin-bottom: 10px;
}

.welcome-text {
    text-align: center;
    font-size: 18px;
    color: #666;
    margin-bottom: 30px;
}

.login-type-switch {
    display: flex;
    background-color: #f5f5f5;
    border-radius: 8px;
    margin-bottom: 20px;
    overflow: hidden;
}

.type-item {
    flex: 1;
    text-align: center;
    padding: 10px 0;
    font-size: 14px;
    color: #666;
    cursor: pointer;
    transition: all 0.3s;
}

.type-item.active {
    background-color: #ff6b6b;
    color: white;
}

.form-group {
    margin-bottom: 20px;
}

label {
    display: block;
    margin-bottom: 8px;
    font-size: 14px;
    color: #666;
}

input {
    width: 100%;
    padding: 12px 15px;
    border: 1px solid #ddd;
    border-radius: 8px;
    font-size: 16px;
    transition: border-color 0.3s;
    box-sizing: border-box;
}

input:focus {
    border-color: #ff6b6b;
    outline: none;
}

.contact-options {
    display: flex;
    align-items: center;
    margin-bottom: 5px;
}

.contact-item {
    flex: 1;
}

.contact-divider {
    margin: 0 15px;
    color: #999;
    font-size: 14px;
}

.error-message {
    color: #ff4d4f;
    font-size: 12px;
    margin-top: 5px;
}

.form-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    font-size: 14px;
}

.remember-me {
    display: flex;
    align-items: center;
}

.remember-me input {
    width: auto;
    margin-right: 5px;
}

.forgot-password {
    color: #ff6b6b;
    text-decoration: none;
}

.btn-login, .btn-register {
    width: 100%;
    padding: 12px;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: background-color 0.3s;
}

.btn-login {
    background-color: #ff6b6b;
    color: white;
    margin-bottom: 30px;
}

.btn-login:hover {
    background-color: #ff5252;
}

.btn-register {
    background-color: #ff6b6b;
    color: white;
}

.btn-register:hover {
    background-color: #ff5252;
}

.other-login {
    margin-top: 20px;
}

.divider {
    display: flex;
    align-items: center;
    color: #999;
    font-size: 14px;
    margin-bottom: 20px;
}

.divider::before, .divider::after {
    content: "";
    flex: 1;
    border-bottom: 1px solid #eee;
}

.divider span {
    padding: 0 10px;
}

.social-login {
    display: flex;
    justify-content: space-around;
}

.social-icon {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: #666;
    cursor: pointer;
    transition: background-color 0.3s;
}

.social-icon:hover {
    background-color: #eee;
}
</style>